﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
//using System.Linq;
using System.Text;
using System.Windows.Forms;
//using System.Data.SqlServerCe;

namespace MercuryFE
{
    public partial class frmSearch : Form
    {
        private int _menuID;
        private string _sourceFolder;
        public bool useWizard { get; set; }


        public frmSearch(int menuID, string sourceFolder)
        {
            InitializeComponent();
            _menuID = menuID;
            _sourceFolder = sourceFolder;
            populateControls();
        }

        private void populateControls()
        {
            bool fileSearch = false;
            if (_menuID == -1)
            {
                // if menuid = -1, then most likely being called by 
                gbSearchWizards.Visible = false;
                fileSearch = true;
                btnRomFileSearch.Visible = true;
                btnCopyMameRomFiles.Visible = true;
                btnSearch.Visible = false;
                btnAddGames.Visible = false;
            }
            else
            {
                gbSearchWizards.Visible = true;
                btnRomFileSearch.Visible = false;
                btnCopyMameRomFiles.Visible = false;
                btnSearch.Visible = true;
                btnAddGames.Visible = true;
            }

            //List<String> emulators = null;
            Dictionary<int, string> emulators = null;

            Dictionary<int, string> mameEmulator = null;

            List<String> nPlayers = null;
            List<String> categories = null;
            List<String> controlTypes = null;
            List<string> manufacturers = null;
            List<string> driverStatus = null;
            List<string> sourceFiles = null;

            LauncherLib.getSearchParameterLookups(ref emulators, ref nPlayers, ref categories, ref controlTypes, ref manufacturers, ref driverStatus, ref sourceFiles, ref mameEmulator);

            cmbEmulator.Items.Clear();
            cmbNPlayers.Items.Clear();
            cmbMameCategory.Items.Clear();
            clbControlType.Items.Clear();
            clbManufacturers.Items.Clear();
            clbDriverStatus.Items.Clear();
            clbBiosFiles.Items.Clear();

            //cmbEmulator.Items.AddRange(emulators);
            cmbEmulator.DisplayMember = "Value";

            if (fileSearch)
            {
                foreach (KeyValuePair<int, string> item in mameEmulator)
                {
                    cmbEmulator.Items.Add(item);
                }

            }
            else
            {
                foreach (KeyValuePair<int, string> item in emulators)
                {
                    cmbEmulator.Items.Add(item);
                }
            }


            cmbNPlayers.Items.AddRange(nPlayers.ToArray());
            cmbMameCategory.Items.AddRange(categories.ToArray());

            cmbEmulator.SelectedIndex = 0;
            cmbNPlayers.SelectedIndex = 0;
            cmbMameCategory.SelectedIndex = 0;


            foreach (string controlType in controlTypes)
                clbControlType.Items.Add(controlType, true); // check all by default

            foreach(string manufacturer in manufacturers)
                clbManufacturers.Items.Add(manufacturer, true);

            foreach (string sourceFile in sourceFiles)
                clbBiosFiles.Items.Add(sourceFile, true);


            foreach (string driverStat in driverStatus)
            {
                if(driverStat=="good")
                    clbDriverStatus.Items.Add(driverStat, true);
                else
                    clbDriverStatus.Items.Add(driverStat, false);
            }


            cmbNameOperator.SelectedIndex = 0;
            cmbRomFileOperator.SelectedIndex = 0;


        }

        private string[] getCheckedListBoxItems(CheckedListBox clb)
        {
            // shortcut - if all checked, just return null, so won't be included in search
            if (clb.CheckedItems.Count == clb.Items.Count)
                return null;


            List<string> itemList = new List<string>();
            foreach (string item in clb.CheckedItems)
                itemList.Add(item);

            return itemList.ToArray();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            this.Enabled = false;
            string[] driverStatus = getCheckedListBoxItems(clbDriverStatus);
            string[] controlType = getCheckedListBoxItems(clbControlType);
            string[] manufacturers = getCheckedListBoxItems(clbManufacturers);
            string[] sourceFiles = getCheckedListBoxItems(clbBiosFiles);

            int maxNumButtons = int.Parse(nudMaxButtons.Value.ToString());

            KeyValuePair<int, string> emulator = (KeyValuePair<int, string>)cmbEmulator.SelectedItem;

            DataTable searchGames =
            LauncherLib.searchGames(
                  emulator //(cmbEmulator.SelectedIndex == 0 ? "" : cmbEmulator.SelectedItem.ToString())
                , tbName.Text
                , (LauncherLib.SearchType)Enum.Parse(typeof(LauncherLib.SearchType), cmbNameOperator.SelectedItem.ToString())
                                , tbRomFile.Text
                , (LauncherLib.SearchType)Enum.Parse(typeof(LauncherLib.SearchType), cmbRomFileOperator.SelectedItem.ToString())
                , (cmbNPlayers.SelectedIndex == 0 ? "" : cmbNPlayers.SelectedItem.ToString())
                , (cmbMameCategory.SelectedIndex == 0 ? "" : cmbMameCategory.SelectedItem.ToString())
                , chkIncludeClones.Checked
                , driverStatus
                , controlType
                , manufacturers
                , maxNumButtons
                , sourceFiles
                );

            

            dgvGameSearch.DataSource = searchGames;
            dgvGameSearch.Columns["GameID"].Visible = false;
            lblSearchGamesResults.Text = "Number of Games returned: " + searchGames.Rows.Count.ToString();
            this.Enabled = true;
        }

        private void btnAddGames_Click(object sender, EventArgs e)
        {
            DataTable searchGames = (DataTable)dgvGameSearch.DataSource;

            string error = "";
            if (!LauncherLib.addGames(_menuID, searchGames, ref error))
            {
                MessageBox.Show("Error adding games to menu" + Environment.NewLine + error, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //return;
            }


            this.Close();
        }

        private void chkControlTypeAll_CheckedChanged(object sender, EventArgs e)
        {
            for(int i = 0 ; i < clbControlType.Items.Count; i++) {
                clbControlType.SetItemChecked(i, chkControlTypeAll.Checked);
            }
        }

        private void chkManufacturersAll_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < clbManufacturers.Items.Count; i++)
            {
                clbManufacturers.SetItemChecked(i, chkManufacturersAll.Checked);
            }
        }

        private void chkDriverStatusAll_CheckedChanged(object sender, EventArgs e)
        {

            for (int i = 0; i < clbDriverStatus.Items.Count; i++)
            {
                clbDriverStatus.SetItemChecked(i, chkDriverStatusAll.Checked);
            }
        }

        private void cmbEmulator_SelectedIndexChanged(object sender, EventArgs e)
        {
            //string emulator = cmbEmulator.SelectedItem == null ? "" : cmbEmulator.SelectedItem.ToString();
            KeyValuePair<int, string> emulator = (KeyValuePair<int, string>)cmbEmulator.SelectedItem;

            bool IsEmulatorMame = LauncherLib.IsEmulatorMame(emulator.Key);

            if (IsEmulatorMame || emulator.Key == -1)
            {
                gbMame.Enabled = true;
                if (IsEmulatorMame)
                    btnCategoryWizard.Enabled = true;
                else
                    btnCategoryWizard.Enabled = false;
            }
            else
            {
                gbMame.Enabled = false;
                btnCategoryWizard.Enabled = false;

            }
        }

        private void btnCategoryWizard_Click(object sender, EventArgs e)
        {
            this.Enabled = false;
            string[] driverStatus = getCheckedListBoxItems(clbDriverStatus);
            string[] controlType = getCheckedListBoxItems(clbControlType);
            string[] manufacturers = getCheckedListBoxItems(clbManufacturers);
            string[] sourceFiles = getCheckedListBoxItems(clbBiosFiles);

            KeyValuePair<int, string> emulator = (KeyValuePair<int, string>)cmbEmulator.SelectedItem;

            int maxNumButtons = int.Parse(nudMaxButtons.Value.ToString());

            LauncherLib.populateMameCategories_wizard(
                 _menuID
                 , emulator
                , tbName.Text
                , (LauncherLib.SearchType)Enum.Parse(typeof(LauncherLib.SearchType), cmbNameOperator.SelectedItem.ToString())
                                , tbRomFile.Text
                , (LauncherLib.SearchType)Enum.Parse(typeof(LauncherLib.SearchType), cmbRomFileOperator.SelectedItem.ToString())
                , (cmbNPlayers.SelectedIndex == 0 ? "" : cmbNPlayers.SelectedItem.ToString())
                , chkIncludeClones.Checked
                , driverStatus
                , controlType
                , manufacturers
                , maxNumButtons
                , sourceFiles
                );

            useWizard = true;
            this.Enabled = true;
            this.Close();
        }

        private void btnAlphabetWizard_Click(object sender, EventArgs e)
        {
            this.Enabled = false;
            string[] driverStatus = getCheckedListBoxItems(clbDriverStatus);
            string[] controlType = getCheckedListBoxItems(clbControlType);
            string[] manufacturers = getCheckedListBoxItems(clbManufacturers);
            string[] sourceFiles = getCheckedListBoxItems(clbBiosFiles);


            KeyValuePair<int, string> emulator = (KeyValuePair<int, string>)cmbEmulator.SelectedItem;

            int maxNumButtons = int.Parse(nudMaxButtons.Value.ToString());

            LauncherLib.populateGamesByLetter_wizard(
                 _menuID
                 , emulator //(cmbEmulator.SelectedIndex == 0 ? "" : cmbEmulator.SelectedItem.ToString())
                , tbName.Text
                , (LauncherLib.SearchType)Enum.Parse(typeof(LauncherLib.SearchType), cmbNameOperator.SelectedItem.ToString())
                                , tbRomFile.Text
                , (LauncherLib.SearchType)Enum.Parse(typeof(LauncherLib.SearchType), cmbRomFileOperator.SelectedItem.ToString())
                , (cmbNPlayers.SelectedIndex == 0 ? "" : cmbNPlayers.SelectedItem.ToString())
                , (cmbMameCategory.SelectedIndex == 0 ? "" : cmbMameCategory.SelectedItem.ToString())
               
                , chkIncludeClones.Checked
                , driverStatus
                , controlType
                , manufacturers
                , maxNumButtons
                , sourceFiles
                );

            useWizard = true;
            this.Enabled = true;
            this.Close();
        }

        private void chkSourceFilesAll_CheckedChanged(object sender, EventArgs e)
        {

            for (int i = 0; i < clbBiosFiles.Items.Count; i++)
            {
                clbBiosFiles.SetItemChecked(i, chkBiosFilesAll.Checked);
            }
        }

        private void btnRomFileSearch_Click(object sender, EventArgs e)
        {
            this.Enabled = false;
            string[] driverStatus = getCheckedListBoxItems(clbDriverStatus);
            string[] controlType = getCheckedListBoxItems(clbControlType);
            string[] manufacturers = getCheckedListBoxItems(clbManufacturers);
            string[] sourceFiles = getCheckedListBoxItems(clbBiosFiles);

            int maxNumButtons = int.Parse(nudMaxButtons.Value.ToString());

            KeyValuePair<int, string> emulator = (KeyValuePair<int, string>)cmbEmulator.SelectedItem;

            

            DataTable searchGames =
            LauncherLib.searchMameRomFiles(
                _sourceFolder
                //, emulator //(cmbEmulator.SelectedIndex == 0 ? "" : cmbEmulator.SelectedItem.ToString())
                , tbName.Text
                , (LauncherLib.SearchType)Enum.Parse(typeof(LauncherLib.SearchType), cmbNameOperator.SelectedItem.ToString())
                                , tbRomFile.Text
                , (LauncherLib.SearchType)Enum.Parse(typeof(LauncherLib.SearchType), cmbRomFileOperator.SelectedItem.ToString())
                , (cmbNPlayers.SelectedIndex == 0 ? "" : cmbNPlayers.SelectedItem.ToString())
                , (cmbMameCategory.SelectedIndex == 0 ? "" : cmbMameCategory.SelectedItem.ToString())
                , chkIncludeClones.Checked
                , driverStatus
                , controlType
                , manufacturers
                , maxNumButtons
                , sourceFiles
                );



            dgvGameSearch.DataSource = searchGames;

            foreach (DataGridViewRow row in dgvGameSearch.Rows)
            {
                if(!(bool)row.Cells["Valid"].Value)
                    row.DefaultCellStyle.BackColor = Color.PaleVioletRed;
            }
            //dgvGameSearch.Columns["MameRomID"].Visible = false;
            lblSearchGamesResults.Text = "Number of Games returned: " + searchGames.Rows.Count.ToString();
            this.Enabled = true;
        }

        private void btnCopyMameRomFiles_Click(object sender, EventArgs e)
        {
            KeyValuePair<int, string> emulator = (KeyValuePair<int, string>)cmbEmulator.SelectedItem;
            DataTable searchGames = (DataTable)dgvGameSearch.DataSource;
    
            string error = "";
            if (!LauncherLib.copyMameRomFiles(searchGames, emulator.Key, ref error))
            {
                MessageBox.Show("Error copying rom files" + Environment.NewLine + error, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }


            //LauncherLib.copyRomFiles(_menuID, searchGames);
            this.Close();
        }



    }
}
